<template>
  <div class="biz-container">
    <table-layout :haveSider="false">
      <template #searchBox>
        <search-layout
          :formInfos="q_formInfos"
          :formDatas="q_formDatas"
          message=""
          @onFind="onFind"
        ></search-layout>
      </template>
      <template #batchOperat>
        <batch-operat-btn 
          :addData="true" @onAddData="onAddData" 
          :delectData="true" @onDelectData="onDelectData"
          :importData="true" @onImportData="onImportData">
          <template #cusBtn>
            <export-excel ref="export" @getExcelData="onExportData"></export-excel>
          </template>
        </batch-operat-btn>
      </template>
      <template #tableList="slotData">
        <a-list-table
          :columns="columns"
          :tableData="listdata"
          :pagination="pagination"
          :isSelecttion="true"
          :loading="loading"
          :scroll="{y:slotData.tableHeight}"
          @onTableChange="handleTableChange"
          @onselectChange="onselectChange"
          @onAction="onAction"
          @onTouchCell="onTouchCell"
        >
        </a-list-table>
      </template>
    </table-layout>
    <saleGoodsModal ref="modal" @ok="handleModalSaveOk" @close="handleModalCancel" />
    <viewModal ref="viewModal" @ok="handleModalSaveOk" @close="handleModalCancel" />
    <import-excel ref="import"  @onSubmit="onSubmitExcel"  />
  </div>
</template>

<script>
import searchLayout from '@/views/app/biz/common/searchLayout'
import batchOperatBtn from '@/views/app/biz/common/batchOperatBtn'
import tableLayout from '@/views/app/biz/common/index'
import aListInfo from '@/views/app/biz/common/aListInfo'
import aListTable from '@/views/app/biz/common/aListTable'
import saleGoodsModal from './PlatformGoodsModal'
import viewModal from './viewModal'
import exportExcel from '@/views/app/biz/common/exportExcel/index'
import importExcel from '@/views/app/biz/common/importExcel'
import {
  getByConditions,
  getByConditionsCount,
  deleteInfo
} from './PlatformData'


// 字段列表
const columns = [
//   { title: '数据有效区域(国、省、市、县、院)', dataIndex: 'areaUse', key: 'areaUse', align: 'center' },
  { title: '商品自编码', dataIndex: 'code', key: 'code', align: 'center' },
  { title: '品名', dataIndex: 'productNameZh', key: 'productNameZh', align: 'center', scopedSlots: { customRender: 'column' }},
//   { title: '英文名称', dataIndex: 'productNameEn', key: 'productNameEn', align: 'center' },
  { title: '通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
  { title: '一级分类', dataIndex: 'first', key: 'first', align: 'center' },
  { title: '二级分类', dataIndex: 'second', key: 'second', align: 'center' },
  { title: '三级分类', dataIndex: 'third', key: 'third', align: 'center' },
//   { title: '规格（特征、参数）', dataIndex: 'spec', key: 'spec', align: 'center' },
//   { title: '型号(剂型)', dataIndex: 'model', key: 'model', align: 'center' },
//   { title: '医保代码', dataIndex: 'medicareCode',key: 'medicareCode',   align:'center', },
//   { title: '描述', dataIndex: 'disc', key: 'disc', align: 'center' },
  { title: '品牌', dataIndex: 'brand', key: 'brand', align:'center' },
//   { title: '上市许可持有企业社会编码', dataIndex: 'mahCode', key: 'mahCode', align: 'center' },
//   { title: '上市许可持有企业中文名', dataIndex: 'mahZh', key: 'mahZh',align:'center'  },
//   { title: '上市许可持有企业英文名', dataIndex: 'mahEn', key: 'mahEn', align: 'center' },
//   { title: '生产企业社会编码', dataIndex: 'manufacturerCode', key: 'manufacturerCode', align: 'center' },
  { title: '生产企业名称', dataIndex: 'manufacturerZh', key: 'manufacturerZh',align:'center'  },
//   { title: '生产企业英文名称', dataIndex: 'manufacturerEn', key: 'manufacturerEn', align: 'center' },
  { title: '产地', dataIndex: 'origin', key: 'origin', align: 'center' },
//   { title: '产品类别(字典medicalCategory)', dataIndex: 'category', key: 'category', align: 'center' },
//   { title: '计量单位', dataIndex: 'measurement', key: 'measurement', align: 'center' },
//   { title: '药品本位码', dataIndex: 'sdc', key: 'sdc', align: 'center' },
//   { title: '当前批准类型(字典medicalApprovalType)', dataIndex: 'approvalType', key: 'approvalType', align: 'center' },
  { title: '注册证号', dataIndex: 'approvalNum', key: 'approvalNum', align: 'center' },
//   { title: '当前有效期始', dataIndex: 'approvalDate', key: 'approvalDate', align: 'center' },
  { title: '有效期止', dataIndex: 'validDate', key: 'validDate', align: 'center' },
  { title: '状态', dataIndex: 'state', key: 'state', align: 'center' },
  { title: '结算方式', dataIndex: 'settlement', key: 'settlement', align: 'center' },
//   { title: '阳采编码', dataIndex: 'acquisitionCode', key: 'acquisitionCode', align: 'center' },
  {
    title: '操作',
    dataIndex: 'action',
    key: 'operation',
    width: 150,
    align: 'center',
    scopedSlots: { customRender: 'action' },
  },
]
// 查询表单
const q_formInfos = [
  { label: '商品名称', name: 'productNameZh', type: 'input', placeholder: '品名' },
  { label: '商品状态',name: 'state',type: 'dicselect',dicName:'medicalProdState',placeholder: '商品状态'},
  { label: ['查询', '重置'], type: 'botton' },
]
// 查询表单绑定数据
const q_formDatas = {
  productNameZh: null,
  settlement:null,
  state:null
}


export default {
  components: {
    searchLayout,
    batchOperatBtn,
    tableLayout,
    aListInfo,
    aListTable,
    exportExcel,
    saleGoodsModal,
    viewModal,
    importExcel
  },
  data() {
    return {
      columns: columns,
      listdata: [],
      loading: false,
      pagination: {
        //分页配置
        current: 1, //当前页码 current
        pageSize: 10, //每页显示条数 pageSize
        total: 1,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['2', '10', '50', '100'],
      },
      q_formInfos: q_formInfos,
      q_formDatas: q_formDatas,
      pData: {}, // 条件查询参数
      selectedRowKeys:[],
      selectedRows:[],
    }
  },
  computed: {},

  created() {
    this.getTotal()
    this.getList(this.q_formDatas)
  },
  methods: {
    // 初始化页面时得到总数
    async getTotal() {
      let pages = ''
      pages = await getByConditionsCount(this.q_formDatas)
      console.log(pages)
      if (pages && pages.code && pages.code === 'C1') {
        const pagination = { ...this.pagination }
        pagination.total = pages.data
        this.pagination = pagination
        this.pagination.showTotal =  (showTotal) => {return `共 ${showTotal} 条`}
      }
    },
    // 初始化查询时的数据列表
    async getList(params) {
      console.log('请求列表时传入的数据', params)
      this.loading = true
      this.listdata = []
      let res = ''
      res = await getByConditions(params, this.pagination)
      this.loading = false
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        const resdata = res.data
         for (let item of resdata) {
            this.listdata.push({
               key: item.pid,
               action: ['编辑','删除'],
               ...item
               }
            )
         }
      } else {
        this.listdata = []
      }
      this.loading = false
    },
    // 新增按钮 点击了新增
    onAddData() {
      console.log('点击了新增')
      this.$refs.modal.addModal()
    },
    // 关闭模态详细框
    handleModalCancel() {
    },
    // 模态详细框提交按钮
    handleModalSaveOk() {
      this.getList(this.q_formDatas)
    },
    // 操作按钮
    onAction(text, record, index) {
      
      console.log('点击list中的操作按钮', text, record, index)
      if (text == '编辑') {
        //编辑
        this.$refs.modal.editModal(record.pid)
      }else if(text == '删除'){
        this.showConfirm(record,'1')
      }
    },
    showConfirm(val,type) {
      let datas=[]
      if(type=='1'){
        datas[0]=val
      }else{
        datas=val
      }
      const that = this;
      this.$confirm({
        title: '是否确认删除？',
        content: '删除后不可恢复！',
        onOk() {
          let reqArr=[]
          let key='self'
          for (const item of datas) {
            reqArr.push(that.pushGoods(item))
          }
          return Promise.all(reqArr).then(res => {
            console.log(res);
            for (const item of res) {
              console.log(item);
              if (item && item.code && item.code === 'C1' && item.data) {
                that.$message.success({ content:'商品'+item.data.productNameZh+ '删除成功', duration: 3 })
              } else {
                that.$message.error({ content:'商品'+item.data.productNameZh+ '删除失败，原因：'+item.message, duration: 3 })
              }
            }
            that.handleModalSaveOk()
          }).catch(err => {
            that.$message.error({ content:'操作出错:'+err, duration: 3 })
          })
        },
        onCancel() {},
      });
    },
    async pushGoods(val){
      let res = await deleteInfo(val)
      return res
    },
    // 触发改变页码,筛选,排序时的回调
    handleTableChange(pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.pagination.pageSize = pagination.pageSize
      this.getList(this.q_formDatas)
    },
    // 查询按钮
    onFind (){
      this.pagination.current = 1
      this.getTotal()
      this.getList(this.q_formDatas)
    },
    onTouchCell(text, record, index){
      this.$refs.viewModal.showModal(record.pid,record)
    },
    // 多选批量操作
    onselectChange(selectedRowKeys,selectedRows ) {
      this.selectedRowKeys=selectedRowKeys
      this.selectedRows=selectedRows
    },
    onDelectData(){
      if(this.selectedRows.length){
        this.showConfirm(this.selectedRows)
      }else{
        this.$message.warning({ content:'未选择要删除的商品', duration: 3 })
      }
    },
    //点击导入数据
    onImportData(){
      //导入excel预览列表的columns,要求title值和excel表头值一一对应
      const excelColumns=[
          { title: '序号', dataIndex: 'key', key: 'key', align: 'center',},
          { title: '一级分类（学科、\n品类）', dataIndex: 'first', key: 'first', align: 'center',},
          { title: '二级分类（用途、品\n目）', dataIndex: 'second', key: 'second', align: 'center',},
          { title: '三级分类（部位、功能、\n品种）', dataIndex: 'third', key: 'third', align: 'center', },
          { title: '医保耗材代码', dataIndex: 'medicareCode', key: 'medicareCode', align: 'center', },
          { title: '医保通用名', dataIndex: 'commonName', key: 'commonName', align: 'center' },
          { title: '耗材材质', dataIndex: 'disc', key: 'disc', align: 'center' },
          { title: '耗材生产企业', dataIndex: 'manufacturerZh', key: 'manufacturerZh', align: 'center' },
          { title: '规格（特征、参数）', dataIndex: 'spec', key: 'spec', align: 'center', },
          { title: '操作',dataIndex: 'action',width: 100,key: 'operation',align: 'center',scopedSlots: { customRender: 'action' },},
      ]
      this.$refs.import.showModal(excelColumns)
    },
    //提交导入数据
    async onSubmitExcel(val){
      console.log(val);
      //执行提交数据代码，提交成功后执行this.$refs.import.closeModal2()
      let key = 'updatable'
      this.$message.loading({ content: '正在导入中', key })
      // let res = await saveInfo(val)
      let res = {code:'C1',data:[]}
      console.log(res)
      if (res && res.code && res.code === 'C1' && res.data) {
        this.$message.success({ content: '导入成功',key, duration: 3 })
        this.$refs.import.closeModal2()
        this.getList(this.q_formDatas)
      } else {
        this.$message.error({ content: '导入失败,请稍后再试',key, duration: 3 })
      }
      
    },
    //点击导出数据
    onExportData(){
      //如需请求数据，则在此请求数据后执行以下
      let listName="基础商品信息"
      let listHeader=['商品自编码','商品名称','一级分类（学科、品类）','二级分类（用途、品目）','三级分类（部位、功能、品种）','品牌']
      let listField=['code','productNameZh','first','second','third','brand']
      let exportList=this.listdata
      this.$refs.export.setData(listName,listHeader,listField,exportList)
    }
    
  },
}
</script>

<style>
</style>